﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using TokenDemo2.Models;

namespace TokenDemo2.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController:Controller
    {
        private readonly IConfiguration _configuration;

        public LoginController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpPost]
        [Route("login")]
        public IActionResult Login([FromBody] User  user)
        {
            if (user.Username.Equals("admin") && user.Password.Equals("admin"))
            {
                user.Id = Guid.NewGuid().ToString();
                string token = CreateJWTToken(user);
                return Ok(token);
            }

            return BadRequest("User or Password is wrong");
        }

        private string CreateJWTToken(User user)
        {
            var securityKey = Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]);

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username)
            };

            var credentials = new SigningCredentials(new SymmetricSecurityKey(securityKey), SecurityAlgorithms.HmacSha256);

            var JWTToken = new JwtSecurityToken(_configuration["JWT:Issuer"],
                _configuration["JWT:Issuer"],
                claims,
                expires: DateTime.Now.AddDays(5),
                signingCredentials: credentials);
            return new JwtSecurityTokenHandler().WriteToken(JWTToken);
        }
    }
}
